package com.pinyoumei.app.activity.wallet;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.BaseFragmentCurrency;
import com.pinyoumei.app.adapter.CouponAdapter;
import com.pinyoumei.app.adapter.UserBalanceAdapter;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WalletIncomeFragment extends BaseFragmentCurrency {

    private int mTitle = 0;
    private int page = 1;
    private UserBalanceAdapter userBalanceAdapter;
    private RecyclerView recyclerView;
    private String baseUrl = "";
    List<UserBalanceBean.ResultBean.UserBalanceDto> list = new ArrayList<>();

    public static WalletIncomeFragment getInstance(int title) {
        WalletIncomeFragment sf = new WalletIncomeFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    protected int layoutId() {
        return R.layout.wallet_income_view;
    }

    @Override
    protected void initView(View view) {
        Utils.startTime = "";
        Utils.endTime = "";
        EventBusUtils.register(this);
        recyclerView = view.findViewById(R.id.wiv_rec_list);

        SmartRefreshLayout swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);

        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL));
        userBalanceAdapter = new UserBalanceAdapter(R.layout.user_balance_item,null);
        userBalanceAdapter.getContext(getContext());
        userBalanceAdapter.getInputType(1);
        userBalanceAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        recyclerView.setAdapter(userBalanceAdapter);

        //首页数据下拉刷新监听
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                list.clear();
                page = 1;
                myWalletRequest(SPUtils.getAppUserId(getContext()));
                refreshLayout.finishRefresh();

            }
        });
        swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                myWalletRequest(SPUtils.getAppUserId(getContext()));
                refreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    protected void initData(Context context) {
        if(mTitle == 1){
            baseUrl = Constants.userBalance;
        }else if (mTitle == 2){
            baseUrl = Constants.userHappyCoupon;
        }else if (mTitle ==3){
            baseUrl = Constants.userScore;
        }
        myWalletRequest(SPUtils.getAppUserId(getContext()));
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void myWalletRequest(String user_id){
        Map<String, Object> map = new HashMap<>();
        map.put("user_id",user_id);
        map.put("query_time_begin", Utils.startTime);
        map.put("query_time_end",Utils.endTime);
        map.put("deal_type","1");
        map.put("page",page);
        map.put("limit","10");
        OkGo.<String>post(baseUrl)
                .params("user_id", user_id)
                .params("query_time_begin", Utils.startTime)
                .params("query_time_end", Utils.endTime)
                .params("deal_type", "1")
                .params("page", page)
                .params("limit", "10")
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDailog.dismiss();
                        UserBalanceBean userBalanceBean = gson.fromJson(response.body(), UserBalanceBean.class);
                        if (userBalanceBean.getCode() >= 0) {
                            if(page == 1){
                                list.clear();
                            }
                           list.addAll(userBalanceBean.getResult().getData_list());
                            userBalanceAdapter.setNewData(list);
                            View notDataView2 = getLayoutInflater().inflate(R.layout.item_empty_view, (ViewGroup) recyclerView.getParent(), false);
                            userBalanceAdapter.setEmptyView(notDataView2);
                        } else {
                            ToastUtils.showShort(userBalanceBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(String message) {
        if(TextUtils.equals(message,"shuaxin")){
            myWalletRequest(SPUtils.getAppUserId(getContext()));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }
}
